<?php
/**
 * 订单文件
 *
 * @author lwb
 */

namespace app\wechat\controller;

use Custom\Constant;
use think\Log;

class Order extends Common {

    public function __construct() {
        parent::__construct();
    }
    /**
     * 提交订单
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-12T11:46:54+0800
     * @param    [type]
     * @return   [type]
     * 添加测试程序流程 出资方为空置为固定220
     * update add zenghu 2018年12月5日16:51:52 添加当非蚂蚁账单模式时 下单前需要验证机构余额
     */
    public function createOrder($params){
        $result = $this->getWS('credit', 'apply@checkApply', ['u_code'=>$this->uid, 'partner_type'=>'1']);
        if($result['status'] != '2000'){
            return $this->parse_data(['code'=>5000, 'msg'=>$result['msg'], 'data'=>['jumpUrl'=>($result['status']=='5001'?'/order/orderlist':'')]]);
        }
        // 判断出资方（此处同一课程同期数多个出资方的话 需要根据规则去判断 以后补充）
        if($params['orderInfo']['fund_type'] == 3){ // 信用卡模式
            $params['orderInfo']['fund_id'] = 220;
        }

        if(empty($params['orderInfo']['b_borrow_amount'])){
            $b_borrow_amount = session('set_amount');
        }else{
            $b_borrow_amount = $params['orderInfo']['b_borrow_amount'];
        }

        $data = [
            'ip' => request()->ip(),
            'partner_id' => session('partner_id'),
            'p_id' => $params['orderInfo']['p_id'],
            'b_period' => $params['orderInfo']['b_period'],
            'fund_id' => $params['orderInfo']['fund_id'],
            'b_borrow_amount' => $b_borrow_amount,
            'u_code' => $this->uid,
            'partner_order_no' => session('order_no')
        ];

        $data['b_sales_id'] = session('qrcode_id');

        if(session('partner_k12')){
            $data['student_name'] = $params['orderInfo']['b_student_name'];
            $data['student_relation'] = $params['orderInfo']['b_student_relation'];
        }
        // 当非蚂蚁账单模式时 下单前需要验证机构余额
        if($data['fund_id'] != 183){
            $productService = $this->getWS('credit', 'Partners@productService', ['p_id'=>$params['orderInfo']['p_id']]);
            if($productService['status'] != '2000'){
                return $this->parse_data(['code'=>'5000', 'msg'=>$productService['msg']]);
            }
            
        }
        //创建订单
        $result = $this->getWS('credit', 'apply@createApply', $data);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }
        session('b_id',$result['result']['b_id']);

        // 如果选择了购买保险则创建订单后写入order表
//        if ($params['isInsurance']) {
            $this->savePartnerOrder($result['result']['b_id'], $params['orderInfo']['p_id']);
//        }

        return $this->parse_data(['data'=>['b_id'=>$result['result']['b_id']]]);
    }

    private function savePartnerOrder($bid, $pid) {
        $uCode = $this->uid;
        $shouldUpdate = false;
        // 根据pid查询产品信息
        $productResult = $this->getWS('credit', 'Product@productInfo', ['pid' => $pid]);
        $product = $productResult['result'];

        // 根据机构ID查询机构信息
        $partnerResult = $this->getWS('credit', 'Aggregate@getPartnerProduct', ['p_id' => $pid]);
        $partner = $partnerResult['result']['0'];

        // 查询保险是否存在
        $insuranceInfo = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['u_code' => $uCode, 'p_id' => $pid, 'pre_insurance_status' => 1]);
        if ($insuranceInfo['result'] && $insuranceInfo['result']['order_num']) {
            $this->getWS('credit', 'Insurance@updatePreInsuranceBid', ['order_num' => $insuranceInfo['result']['order_num'], 'b_id' => $bid]);
            // 查询order是否存在
            $orderInfo = $this->getWS('credit', 'PartnersOrder@partnerSelect', ['order_num' => $insuranceInfo['result']['order_num']]);
            // 如果存在 更新为bid 保险表也更新
            if ($orderInfo['status'] == Constant::SUCCESS_CODE && $orderInfo['result'][0]['id']) {
                $shouldUpdate = true;
            }
        }
        // 如果存在并且bid不为空 则更新该条数据的bid,和用户应该支付金额
        if ($shouldUpdate) {
            $transactionPay = [
                'id' => $orderInfo['result'][0]['id'],
                'b_id' => $bid,
                'amount' => $product['insurance_user_pay'],
                'order_type' => 6
            ];
            // 如果可以显示保险
            if ($product['is_show']) {
                // 支付金额为0，那么，默认支付状态为成功
                if($product['insurance_user_pay'] == 0 || $product['insurance_user_pay'] == '0.00') {
                    $transactionPay['status'] = 2000;
                }
                $partnersOrder = $this->getWS('credit', 'PartnersOrder@partnerInsert', $transactionPay);
                if ($partnersOrder['status'] != '2000') {
                    return ['code' => Constant::FAILED_CODE, 'msg' => '下单失败'];
                }
            }
        }
        
        return ['code' => Constant::SUCCESS_CODE];
    }

    /**
     * 订单列表
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-30T11:10:12+0800
     * @param    string
     */
    public function orderList($params) {
        $result = $this->getWS('credit', 'apply@applyList', ['where' => ['b.u_code' => $this->uid,'b.b_status' => ['egt','1001']], 'listRows' => '10', 'page' => '1']);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取订单列表失败']);
        }
        $data = $result['result']['data'];

        $info = [];
        foreach ($data as $key => $val) {
            //查询学员违约状态，是否违约结清
            $r_status = db("return")->field('r_status')->where("b_id = {$val['b_id']} and r_status = 2 ")->find();
            if($val['b_status'] == 3001){
                $return_status = !empty($r_status)?config('dict.order_repayment_status')[2]:config('dict.order_repayment_status')[3];
            }else{
                $return_status = config('dict.order_status')[$val['b_status']];
            }

            $info[$key]['b_id'] = $val['b_id'];
            $info[$key]['b_borrow_amount'] = $val['b_borrow_amount'];
            $info[$key]['b_period'] = $val['b_period'];

            //计算x+y模式每月利息加服务费
            if($val['p_partner_service'] == 1){
                $service = round($val['b_borrow_amount'] * ($val['p_rate']/100)/$val['p_period'],2);
            }else{
                $service = round($val['b_borrow_amount'] * ($val['p_rate']/100)/$val['p_period'] + $val['p_service_price'],2);
            }

            $info[$key]['month_rent_amt'] =  round($val['b_borrow_amount'] / $val['b_period'] + $service, 2);
            $info[$key]['status'] = $return_status;
            $info[$key]['b_status'] = $val['b_status'];

            //判断 起始时间选择：1、月，2、日（月：指的是下月、推迟2月。日指的是1-28的某一日）
            if($val['partner_repay_time'] == 2){
                $info[$key]['repayment_day'] = $val['partner_repay_day'];
            }else{
                $info[$key]['repayment_day'] = $val['repayment_day']?$val['repayment_day']:min('28',date('d',strtotime("-".$val['p_advance_return_day']." days",strtotime($val['start_rent_date']))));
            }

            $info[$key]['partner_name'] = $val['partner_name'];
            $info[$key]['order_no'] = orderNo($val['b_id'],$val['b_apply_time']);
            $info[$key]['partner_type'] = $val['partner_type'];
            $info[$key]['status_ico'] = config('dict.order_status_ico')[$val['b_status']];
            $info[$key]['p_name'] = $val['p_name'];
            $info[$key]['u_true_name'] = $val['u_true_name'];
            $info[$key]['bt_remark'] = $val['bt_remark'];
            //交费方式（ 1等额本息，2等本等息, 3等额本金，4x+y模式）
            $info[$key]['p_return_type'] = $val['p_return_type'];
            if($val['p_return_type'] == 4){
                $info[$key]['p_x_month'] = $val['p_x_month'];
                $info[$key]['p_y_month'] = $val['p_y_month'];
                //计算x每月的金额
                $info[$key]['x_amount'] = round($val['b_borrow_amount'] * ($val['p_x_proportion']/100)/$val['p_x_month']+$service, 2);
                //计算x每月的金额
                $info[$key]['y_amount'] = round($val['b_borrow_amount'] * ($val['p_y_proportion']/100)/$val['p_y_month']+$service, 2);
            }

        }
        unset($result);
        
        return $this->parse_data(['data' => $info]);
    }
    
    /**
     * 修改
     */
    public function saveAmount($params) {
        if(empty($params['b_id']) && $this->checkOrder()){
            return $this->parse_data(['code' => 5002, 'msg' => '非法操作']);
        }

        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        $saveData = ['b_borrow_amount' => $params['b_borrow_amount']];
       
        //修改订单状态为审核中
        $result = $this->getWS('credit', 'Apply@updateApply', ['b_id' => $b_id, 'data' =>$saveData]);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '修改金额失败']);
        }

        return $this->parse_data();
    }
    
    /**
     * 提交订单
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-12T11:46:54+0800
     * @param    [type]
     * @return   [type]
     */
    public function saveOrder($params) {
        if(empty($params['b_id']) && $this->checkOrder()){
            return $this->parse_data(['code' => 5002, 'msg' => '非法操作']);
        }

        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        $saveData = ['b_status' => '2000','b_apply_time' => date('Y-m-d H:i:s')];

        $result = $this->getWS('credit', 'apply@applyStatus', ['b_id' => $b_id]);
        if($result['result']['status'] == '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '订单已提交，请勿重复提交']);
        }

        //查询订单的用户信息
        $orderName = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $b_id]);


        //ocr人脸识别是否开启(注：如果审核回退的只有影像资料，不需要判断影像资料是否需要ocr识别。因为当回退的时候已将ocr检验失败的次数清空，所以默认校验成功)
        switch ($params['ocr_open_where']) {
            case 'apply_open': // 正常申请流程时ocr校验的配置
                $config_ocr_open = config('ocr.apply_open');
                break;
            case 'back_open': // 审核回退时ocr校验的配置
                $config_ocr_open = config('ocr.back_open');

                //判断机构配置的自动审核是否会生效。
                //目前只在审核回退时做判断：当机构开启自动审核时，如果审核回退后学员补充资料时的ocr校验未开启，则学员提交后变为人工审核2000；如果ocr校验开启，则自动审核生效。）
                //审核回退后学员补充资料ocr校验开启，校验失败变为1003
                if($config_ocr_open != 'on'){
                    $auto_pay_open = '2';  //自动审单 生效为：1（或者不传参数auto_pay_open）；不生效为：2
                }
                break;
            default:
                // 目前ocr做校验的是正常的申请流程和回退
                $config_ocr_open = 'off';
        }
        if($config_ocr_open == 'on'){
            //通过b_id查询机构id
            $checkOcrData = array(
                'u_code'     => $this->uid,
                'u_b_id'     => $b_id,
                'partner_id' => $result['result']['partner_id'],
            );

            //查询是否需要ocr人脸校验
            $checkOcrResult = $this->checkOcrNum($checkOcrData);

            //如果ocr人脸校验失败的次数超过了机构配置的次数（默认一次），则将订单状态变为 1003 审核失败(OCR人脸)
            if ($checkOcrResult['code'] == 5000) {
                $saveData['b_ocr_desc'] = $checkOcrResult['data'][0]['u_desc'];
                $saveData['b_status'] = '1003';
                $saveData['b_pass_time'] = date('Y-m-d H:i:s');
            }
        }

        //同盾白名单
        if(!in_array($orderName['result']['u_name'],config('white_name'))){

            if(config('credit.open') =='on'){

                if(!in_array($result['result']['status'], ['2001','2003']) && $b_id){
                    //征信
                    $credit = $this->credit(['b_id'=>$b_id]);
                    if(empty($credit)){
                        // 保存操作记录
                        $this->getWS('credit', 'trace@myTrace', [
                            'bId' => $b_id,
                            'uCode' => Constant::TRACE_SYSTEM,
                            'type' => Constant::TRACE_CREDIT_EMPTY
                        ]);
                        return $this->parse_data(['code' => 5000, 'msg' => '征信失败']);
                    }
                    $isTrue = true;
                    $i = 2;
                    do {
                        sleep(3);
                        $tongdun = $this->getWS('channel','Credit@tdQuery',['report_id'=>$credit]);
                        if($tongdun['result']['final_score']>=0){
                            //靖佳特殊处理
                            if($result['result']['partner_id']==217){
                                if( $tongdun['result']['final_score'] > 30 ){
                                    $saveData['b_credit_state'] = '征信未通过，征信分数='.$tongdun['result']['final_score'];
                                    $saveData['b_status'] = '1002';
                                    $saveData['b_pass_time'] = date('Y-m-d H:i:s');
                                }else{
                                    $saveData['b_credit_state'] = '征信通过，征信分数='.$tongdun['result']['final_score'];
                                }
                            }else{
                                if( $tongdun['result']['final_score'] > config('credit.max_score') ){
                                    $saveData['b_credit_state'] = '征信未通过，征信分数='.$tongdun['result']['final_score'];
                                    $saveData['b_status'] = '1002';
                                    $saveData['b_pass_time'] = date('Y-m-d H:i:s');
                                }else{
                                    $saveData['b_credit_state'] = '征信通过，征信分数='.$tongdun['result']['final_score'];
                                }
                            }

                            $isTrue = false;
                            break;
                        }

                    }while($isTrue && $i--);

                    if($tongdun['result']['risk_items']){
                        $creditArr = [
                            'b_id' => $b_id,
                            'u_code' => $this->uid,
                            'risk_item' => 'Tongdun',
                            'risk_content' => json_encode($tongdun['result']['risk_items']),
                        ];
                        $this->getWS('credit', 'Apply@saveCredit', $creditArr);
                    }
                }else{
                    unset($saveData['b_apply_time']);
                }
            }
        }


        if(intval($params['b_borrow_amount']) > 0){
            $saveData['b_borrow_amount'] = $params['b_borrow_amount'];
        }
        //修改订单状态为审核中
        $remark_all = $saveData['b_credit_state'].' '.$saveData['b_ocr_desc'];
        $result = $this->getWS('credit', 'Apply@updateApply', ['b_id' => $b_id, 'data' =>$saveData, 'remark' => $remark_all,'auto_pay_open'=>$auto_pay_open]);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '创建订单失败']);
        }
        //系统拒单给学员和老师发送信息通知
        if($saveData['b_status'] == 1002 || $saveData['b_status'] == 1003){
            $this->sendOrderSms($orderName['result']['u_name'],$orderName['result']['u_true_name'],$orderName['result']['partner_name'],$orderName['result']['partner_contact_phone'],$remark_all);
        }

        //系统通过给学员发送信息通知
        if($result['result']['b_status'] == 2301){
            $this->sendSuccOrderSms($orderName['result']['u_name'],$orderName['result']['partner_name']);
        }

        //提醒审单人员
        $this->sendExOrderSms();

        $ocr_remark = '';
        // 保存操作记录
        if($saveData['b_status'] == '1002'){
            $trace_type = Constant::TRACE_CREDIT_FAILED;
        }else if($saveData['b_status'] == '1003'){
            $trace_type = Constant::TRACE_OCR_FAILED;
            $ocr_remark = $saveData['b_ocr_desc'];
        }else{
            $trace_type = Constant::TRACE_APPLY_SUCCESS;
        }

        $this->getWS('credit', 'trace@myTrace', [
            'bId' => $b_id,
            'uCode' => Constant::TRACE_USER,
            'type' => $trace_type,
            'remark' => $ocr_remark,
        ]);
        // 查询是否购买了保险
        $ret['hasInsurance'] = 0;
        //用户u_code
        $ret['u_code'] =  $this->uid;

        $insurance = $this->getWS('credit', 'PartnersOrder@partnerSelect', ['b_id' => $b_id, 'order_type' => ['neq','8']]);
        // 如果order查询成功，并且存在记录
        if ($insurance['status'] == Constant::SUCCESS_CODE && $insurance['result']) {
            if ($insurance['result'][0]['order_num']) {
                $ret['hasInsurance'] = 1;
                $ret['isPass'] = 0;
                $ret['amount'] = 0;
                $ret['orderNUm'] = $insurance['result'][0]['order_num'];
                // 查询保险是否已经通过
                $partnerInsurance = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['order_num' => $ret['orderNUm']]);
                if ($partnerInsurance['result']) {
                    // 如果pre_insurance_status状态为1标识已经预投保过
                    $ret['isPass'] = $partnerInsurance['result']['pre_insurance_status'] == 1 ? 1 : 0;
                    $ret['amount'] = $partnerInsurance['result']['premium_user'];
                }
                if($ret['isPass']) {
                    // 保存操作记录
                    $this->getWS('credit', 'trace@myTrace', [
                        'bId' => $b_id,
                        'uCode' => Constant::TRACE_USER,
                        'type' => Constant::TRACE_APPLY_INSURANCE
                    ]);
                }
            }
        }
        Log::write($ret, '保存账单成功后查询用户保险表结果', true, 'insurance/');
        session('b_id',null);
        session('partner_id',null);
        session('order_no',null);
        session('order_price',null);
        session('partner_conf', null);
        session('partner_k12', null);
        session('min_age', null);
        session('max_age', null);
        return $this->parse_data(['data' => $ret]);
    }
    
    /**
     * 取消订单
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-12T11:46:54+0800
     * @param    [type]
     * @return   [type]
     */
    public function cancelOrder($params) {
        if(empty($params['b_id']) && $this->checkOrder()){
            return $this->parse_data(['code' => 5002, 'msg' => '非法操作']);
        }

        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        $saveData = ['b_status' => '1001'];
       
        //修改订单状态为取消
        $result = $this->getWS('credit', 'Apply@updateApply', ['b_id' => $b_id, 'data' =>$saveData]);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '取消订单失败']);
        }
        session('b_id',null);
        session('partner_id',null);
        session('order_no',null);
        session('order_price',null);
        session('partner_conf', null);
        session('partner_k12', null);
        session('min_age', null);
        session('max_age', null);
        return $this->parse_data();
    }
    
    /**
     * 申请退租
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-19T15:18:08+0800
     * @param    [type]
     */
    public function refund($params){
        $result = $this->getWS('credit', 'refund@addRefund', ['b_id'=>$params['b_id'],'u_code'=>$params['u_code'],'reason'=>$params['reason']]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }
        return $this->parse_data();
    }
    
    //征信
    protected function credit($params){    
        $apply = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $params['b_id']]);
        if($apply['status'] != '2000'){         
             return $this->parse_data(['code' => 5000, 'msg' => $apply['msg']]);
        }
        $applyInfo = $apply['result'];
        $relation = $this->getWS('ucenter', 'users@relationInfo', ['u_code' => $applyInfo['u_code']]);
        $relationInfo = $relation['result'];
        $data = [
            //姓名
            'u_true_name' =>  $applyInfo['u_true_name'],
            //身份证号
            'u_ident_no' => $applyInfo['u_ident_no'],
            //手机号
            'u_name' => $applyInfo['u_name'],
            //银行卡
            'ub_card_no' => $applyInfo['ub_card_no'],
            //申请借款金额
            'b_borrow_amount' =>  $applyInfo['b_borrow_amount'],
            //申请借款期限
            'b_period' => $applyInfo['b_period'],
            //申请借款日期
            'b_apply_time' => date('Y-m-d',strtotime($applyInfo['b_apply_time'])),
            //邮箱
            'u_email' => $applyInfo['u_email'],
            //QQ
            'u_qq' => $applyInfo['u_qq'],
            //学历
            'u_edu_degree' =>$applyInfo['u_edu_degree'],
            //婚姻
            'u_marriage' =>$applyInfo['u_marriage'],
            //家庭地址
            'u_address' => $applyInfo['u_province'].$applyInfo['u_city'].$applyInfo['u_area'].$applyInfo['u_address'],
            //工作单位
            'com_name' => $applyInfo['cus_flag']=='1' ? $applyInfo['opt_name'] : $applyInfo['com_name'],
            //公司地址
            'com_address' => $applyInfo['uw_province'].$applyInfo['uw_city'].$applyInfo['uw_area'].($applyInfo['cus_flag']=='2'?$applyInfo['com_addr']:$applyInfo['opt_addr']),
            //省
            'u_province'=>$applyInfo['u_province'],
            //市
            'u_city'=>$applyInfo['u_city'],
            //联系人
            'contact' => $relationInfo,
            'purpose' => session('partner_id')?'教育账期':'租房账期',
        ];
        $result = $this->getWS('channel','Credit@tdCredit',$data);
        if($result['status'] != '2000'){
             return false;
        }
        //发送微信消息
        if($applyInfo['open_id']){
            //初始化redis
            $cache = \think\Cache::init();
            $redis = $cache->handler();
            $sendMsg = ['tplName' => 'WX001', 'openId' => $applyInfo['open_id'], 'param' => ['username' => $applyInfo['u_true_name'], 'time' => $applyInfo['b_apply_time'], 'money' => $applyInfo['b_borrow_amount']]];    
            $redis->lpush('mq_wxmsg_keys',json_encode($sendMsg)); 
        }
        return $result['result']['report_id'];
   
    }

}

